package cn.caplike.demo.kafka.consumer;

import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.*;

/**
 * 指定时间消费
 */
public class ConsumerConsumeSince {

    @SuppressWarnings("DuplicatedCode")
    public static void main(String[] args) {
        // 配置
        final Properties properties = getProperties();

        // 创建一个消费者
        try (final KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties)) {
            //noinspection ArraysAsListWithZeroOrOneArgument
            consumer.subscribe(Arrays.asList("first")); // 订阅主题

            // 指定位置进行消费数据
            Set<TopicPartition> assignment = consumer.assignment();
            // 保证分区分配方案已经制定完毕
            while (assignment.isEmpty()) {
                consumer.poll(Duration.ofSeconds(1));
                assignment = consumer.assignment();
            }

            // 把时间转换成 offset
            final HashMap<TopicPartition, Long> topicPartitionTimestamp = new HashMap<>();
            for (TopicPartition topicPartition : assignment) {
                topicPartitionTimestamp.put(topicPartition, System.currentTimeMillis() - 1 * 24 * 3600 * 1000); // 算出当前时刻 1 天前的 offset
            }
            final Map<TopicPartition, OffsetAndTimestamp> topicPartitionOffsetAndTimestampMap = consumer.offsetsForTimes(topicPartitionTimestamp); // 通过事件获取到 offset

            for (TopicPartition topicPartition : assignment) {
                consumer.seek(topicPartition, topicPartitionOffsetAndTimestampMap.get(topicPartition).offset()); // 指定时间进行消费: 把时间转换成 offset
            }

            //noinspection InfiniteLoopStatement
            while (true) {
                final ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(1));
                for (ConsumerRecord<String, String> record : records) {
                    System.out.println("Consumer received: " + record);
                }

                // 手动提交
                consumer.commitAsync();
            }
        }
    }

    private static Properties getProperties() {
        final Properties properties = new Properties();

        // 连接
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "big-data-1:9092,big-data-2:9092,big-data-3:9092");
        // 反序列化
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        // 配置消费者组 ID
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "A consumer " + new Random().nextInt()); // 需要更改消费者组, 不然当前组已经消费到一个 offset, 再次执行就不会看得到消费的记录了

        // 手动提交
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);

        return properties;
    }
}
